package com.xiaobai.frame.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaobai.common.utils.config.page.Query;
import com.xiaobai.common.utils.result.AssertUtils;
import com.xiaobai.common.utils.result.R;
import com.xiaobai.common.utils.result.Result;
import com.xiaobai.common.utils.result.ResultCode;
import com.xiaobai.common.utils.tool.Func;
import com.xiaobai.data.manager.system.DictManager;
import com.xiaobai.frame.service.IDictService;
import com.xiaobai.model.entity.system.Dict;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-06-07
 */
@Service
@RequiredArgsConstructor
public class DictServiceImpl implements IDictService {

    private final DictManager dictManager;

    @Override
    public List<Dict> queryList(List<String> list) {
        if (Func.isNull(list) || list.isEmpty()) {
            return dictManager.list();
        }
        return dictManager.list(new LambdaQueryWrapper<Dict>().in(Dict::getCode, list));
    }

    @Override
    public Object getList(Query query, String type) {
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Func.isNotBlank(query.getKey()), Dict::getCode, query.getKey());
        if (Objects.equals(type, "0")) {
            wrapper.isNotNull(Dict::getParentId);
        } else if (Func.equals(type, "1")) {
            wrapper.isNull(Dict::getParentId);
        }
        return dictManager.page(new Page<>(query.getPage(), query.getPageSize()), wrapper);
    }

    @Override
    public Result addData(Dict dict) {
        dict.setIsDeleted(null);
        if (Func.isNull(dict.getParentId())) {
            Dict one = dictManager.getOne(new LambdaQueryWrapper<Dict>().eq(Dict::getCode, dict.getParentId()), false);
            AssertUtils.isNull(one, ResultCode.SAME_RESOURCES);
        }
        dictManager.save(dict);
        return R.success("新增成功");
    }

    @Override
    public boolean update(Dict dict) {
        Dict one = dictManager.getOne(new LambdaQueryWrapper<Dict>().ne(Dict::getId, dict.getId())
            .isNull(Dict::getParentId)
            .eq(Dict::getCode, dict.getCode()), false);
        AssertUtils.isNull(one, ResultCode.SAME_RESOURCES);
        return dictManager.updateById(dict);
    }
}
